#include "roaditem.h"

#include <QPen>
#include <QDebug>
#include <cmath>
#include "graphicsutilities.h"
#include "point.h"
#include "linesegment.h"
#include "geometryutilities.h"

RoadItem::RoadItem(QGraphicsItem *parent)
  : QGraphicsPathItem(parent),
    mLanesFirstSecond(0),
    mLanesSecondFirst(0),
    mRoadWidth(0)
{
  setZValue(GraphicsUtilities::LAYER_ROAD);
  setBrush(Qt::darkGray);
  setPen(QPen(Qt::darkGray));
}

void RoadItem::setFirst(const GeometryUtilities::Point &first)
{
  mFirst = first;
  createRoad();
}

void RoadItem::setSecond(const GeometryUtilities::Point &second)
{
  mSecond = second;
  createRoad();
}

void RoadItem::setLanesFirstSecond(unsigned int num)
{
  mLanesFirstSecond = num;
  createRoad();
}

void RoadItem::setLanesSecondFirst(unsigned int num)
{
  mLanesSecondFirst = num;
  createRoad();
}

void RoadItem::setRoadWidth(unsigned int w)
{
  mRoadWidth = w;
  createRoad();
}

void RoadItem::createRoad()
{
  GeometryUtilities::LineSegment centerLine(mFirst, mSecond),
                                 negativeOffset(centerLine.toOffset(-mRoadWidth/2)),
                                 positiveOffset(centerLine.toOffset(mRoadWidth/2));

  QPainterPath path;
  path.moveTo(negativeOffset.begin().x(), negativeOffset.begin().y());
  path.lineTo(negativeOffset.end().x(), negativeOffset.end().y());
  path.lineTo(positiveOffset.end().x(), positiveOffset.end().y());
  path.lineTo(positiveOffset.begin().x(), positiveOffset.begin().y());
  path.closeSubpath();
  setPath(path);

  // Lane lines
  qDeleteAll(childItems());
  QPen whiteDash(Qt::DashLine);
  whiteDash.setBrush(Qt::white);
  QPen whiteSolid(Qt::white);
  QPen yellowDash(Qt::DotLine);
  yellowDash.setBrush(Qt::yellow);
  QPen yellowSolid(Qt::yellow);

  QGraphicsLineItem* neg(new QGraphicsLineItem(this));
  neg->setZValue(GraphicsUtilities::LAYER_LANELINE);
  neg->setLine(negativeOffset.toQLineF());
  neg->setPen(whiteSolid);

  QGraphicsLineItem* pos(new QGraphicsLineItem(this));
  pos->setZValue(GraphicsUtilities::LAYER_LANELINE);
  pos->setLine(positiveOffset.toQLineF());
  pos->setPen(whiteSolid);

  unsigned int totalLanes(mLanesFirstSecond+mLanesSecondFirst);
  if (totalLanes)
  {
    unsigned int laneWidth(mRoadWidth/totalLanes);
    for (unsigned int i(  1); i<totalLanes; ++i)
    {
      QGraphicsLineItem* item(new QGraphicsLineItem(this));
      item->setZValue(GraphicsUtilities::LAYER_LANELINE);
      GeometryUtilities::LineSegment line(negativeOffset.toOffset(i*laneWidth));
      item->setLine(line.toQLineF());
      if (i == mLanesFirstSecond)
      {
        item->setPen(yellowSolid);
      }
      else
      {
        item->setPen(whiteDash);
      }
    }
  }
}
